package flc.ast.widget.weather;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;

import com.stark.appwidget.lib.BaseAppWidgetView;
import com.stark.weather.lib.WeatherManager;

public abstract class BaseWeatherWidget extends BaseAppWidgetView {

    protected Handler mHandler;
    protected Runnable taskUpdate;
    private boolean isSuccess = false;

    public BaseWeatherWidget(int appWidgetId) {
        super(appWidgetId);
        //初始化天气
        WeatherManager.initCityData(new WeatherManager.IInitCallback() {
            @Override
            public void onRet(boolean success) {
                isSuccess = success;
            }
        });
    }

    @Override
    public void update(Context context) {
        initInUpdate(context);
        onUpdate(context, isSuccess);
        mHandler.removeCallbacks(taskUpdate);
        mHandler.postDelayed(taskUpdate, 60000);
    }

    protected abstract void onUpdate(Context context, boolean success);

    private void initInUpdate(Context context) {
        if (mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }
        if (taskUpdate == null) {
            taskUpdate = new Runnable() {
                @Override
                public void run() {
                    update(context);
                }
            };
        }
    }

    @Override
    public void destroy() {
        if (mHandler != null) {
            mHandler.removeCallbacks(taskUpdate);
            mHandler = null;
        }
    }
}
